# -*- encoding=utf-8 -*-
import socket
import time
import random
import threading
import pymysql
import configparser

config = configparser.ConfigParser()
config.read('balance_config.ini')

log_file = config['LOG']['log_file']
input_file = config['ACCOUNT']['input_file']
batch_file = config['ACCOUNT']['batch_file']

mysql_host = config['MYSQL']['mysql_host']
mysql_user = config['MYSQL']['mysql_user']
mysql_password = config['MYSQL']['mysql_password']
mysql_db = config['MYSQL']['mysql_db']

ESB_SERVER_HOST = config['ESB']['ESB_SERVER_IP']
ESB_SERVER_PORT = config['ESB']['ESB_SERVER_PORT']
ESB_SERVER_ADDR = (ESB_SERVER_HOST, int(ESB_SERVER_PORT))

def get_last_batch():
    return open(batch_file).read().strip()

def inc_batch():
    next_batch = str(int(get_last_batch())+1)
    open(batch_file, 'w').write(next_batch)
    return next_batch


def log(msg):
    timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
    thread_name = threading.current_thread().getName()
    f = open(log_file, 'a')
    f.write('[' + timestamp + '][' + thread_name + ']' + msg + '\n')
    f.close()

def query_balance(acct):
    trancode = 'xxxx'.ljust(12, ' ')
    BusiType = 'V10   '
    ReqSysID = 'DWHS'
    RespSysID = 'CORE'
    yyyymmdd = time.strftime('%Y%m%d',time.localtime(time.time()))
    hh24miss = time.strftime('%H%M%S',time.localtime(time.time()))
    ServiceId = 'xxxxxxxx '
    ServiceVer = '10'
    ReqSeq = ReqSysID + yyyymmdd + hh24miss + str(random.randrange(100,999))
    ReqDate = yyyymmdd
    ReqTime = hh24miss
    ChannelID = ReqSysID.ljust(8)
    GlobalSeq = ReqSysID + yyyymmdd + hh24miss + str(random.randrange(1000,9999))
    SignFlg = '0'
    MacFlg = '0'
    RetCode = 10 * ' '
    EsbextFlag = 55*' '
    fixed_header = 'V20   ' + ReqSysID + ReqSeq + yyyymmdd + hh24miss + ChannelID + GlobalSeq + RespSysID + ServiceId + ServiceVer + trancode + SignFlg + MacFlg + RetCode + EsbextFlag
    xml_req = open('template.xml').read().strip()
    xml_req = xml_req.replace('${AcctCd}', acct)
    xml_req = xml_req.replace('\n', '')
    data = fixed_header + xml_req
    package_len = str(len(data)).rjust(8, '0')
    data = package_len + data
    log("reqxml:[{}]".format(data))
    server_addr = ESB_SERVER_ADDR
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect(server_addr)
    s.send(data.encode())
    recv = s.recv(65535)
    retdata = recv.decode('utf-8')
    log("respxml:[{}]".format(retdata))
    balance = parse_balance(retdata)
    log("balance:[{}]".format(balance))
    return balance

def parse_balance(data):
    balance = ''
    try:
        balance = data[data.find('<AcctAmt>')+9:data.rfind('</AcctAmt>')]
    except:
        log('解析余额失败[{}]'.format(data))
        balance = ''
    if data.find('不存在') > 0:
        balance = ''
    elif data.find('系统故障') > 0:
        balance = ''
    return balance


def main():
    conn = pymysql.connect(host=mysql_host, user=mysql_user, password=mysql_password, database=mysql_db)
    cur = conn.cursor()
    lines = [x.strip() for x in open(input_file, encoding='utf8').readlines()]
    next_batch = inc_batch()
    log("batch:[{}]".format(next_batch))
    
    for line in lines:
        department, _, _, acctname, acct = line.split('|')
        print(department, acctname, acct)
        start = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
        balance = query_balance(acct)
        log(balance)
        end = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
        record = [department, acct, acctname, balance, start, end, next_batch]
        save_record(cur, record)
    cur.close()
    conn.commit()
    conn.close()

def save_record(cur, record):
    department, acct, acctname, balance, start, end, seq = record
    sql = '''
    insert into balance
    (seq, department, acctname, acct, balance, start, end)
    values
    ('{}', '{}', '{}', '{}', '{}', '{}', '{}')
    '''.format(seq, department, acctname, acct, balance, start, end)
    cur.execute(sql)


if __name__ == '__main__':
    main()
